<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.min.css" rel="stylesheet" />
		<script src="../js/mui.min.js"></script>
		<script type="text/javascript" src="../js/other/jquery-3.2.1.js"></script>
		<script type="text/javascript"  type="text/javascript"  src="../js/other/sql.js"></script>
		<script type="text/javascript">
			mui.init();
			var jq = $.noConflict();
			var sql = window.SQL;
			//var sql = require('../js/other/sql.js');
			//创建数据库
			var db = new sql.Database();

			//获取显示数据库所有数据
			function showTableData() {
				var res = db.exec("SELECT * FROM hello");
				alert(res[0] + " -  " + res[1]);

				// Prepare an sql statement
				var stmt = db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval");

				// Bind values to the parameters and fetch the results of the query
				var result = stmt.getAsObject({
					':aval': 0,
					':bval': 'hello'
				});
				console.log(result); // Will print {a:1, b:'world'}

				writeDb2disk();
			};

			//创建表
			function createTable() {
				var sqlstr = jq('#sqlstr_createtable').val();
				console.log("sqlstr = " + sqlstr);
				db.run(sqlstr);
			};

			//插入数据
			function insertData() {
				var sqlstr = jq('#sqlstr_insertdata').val();
				console.log("sqlstr = " + sqlstr);
				db.run(sqlstr);
			};

			//把数据库写入磁盘
			function writeDb2disk() {
				var fs = require("fs");
				// [...] (create the database)
				var data = db.export();
				var buffer = new Buffer(data);
				fs.writeFileSync("filename.sqlite", buffer);
			};
		</script>
		<!--
        	作者：460575807@qq.com
        	时间：2017-07-18
        	描述：https://github.com/kripken/sql.js
        -->
		<style>
			input {
				font-size: 12px;
			}
		</style>
	</head>

	<body>
		<div class="mui-content" align="center">
			<div class="mui-card" style="padding: 5px;">
				基于sqlite的sql.js framework
				<br /> https://github.com/kripken/sql.js
			</div>

			<div style="margin-bottom: 5px;">
				<button id="btn_show" class="mui-btn" style="font-size: 12px;" onclick="showTableData()">查看表数据</button>
			</div>

			<div>
				<table width="100%">
					<tr>
						<td><input type="text" id="sqlstr_createtable" value="CREATE TABLE hello (a int, b char);" /></td>
					</tr>
					<tr align="center">
						<td><button onclick="createTable()">创建表</button></td>
					</tr>
					<tr>
						<td><input type="text" id="sqlstr_insertdata" value="INSERT INTO hello VALUES (0, 'hello');" /></td>
					</tr>
					<tr align="center">
						<td><button onclick="insertData()">插入数据</button></td>
					</tr>
				</table>
			</div>
		</div>
	</body>

</html>